package Test;

import entity.User;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;

public class TestTwo {
    public static void main(String[] args) throws Exception {
        // 1. 获取Class对象
        Class<User> userClass = User.class;

        // Constructor方式
        Constructor<User> constructor = userClass.getConstructor(int.class, String.class);
        User user2 = constructor.newInstance(20,"李五");

        // 访问属性
        Field nameField = userClass.getDeclaredField("name");
        nameField.setAccessible(true); // 禁止访问检查，允许操作私有属性
        nameField.set(user2, "李四"); // 赋值
        String name = (String) nameField.get(user2); // 取值
        System.out.println("姓名：" + name);

        Field ageField = userClass.getDeclaredField("age");
        ageField.setAccessible(true);
        ageField.set(user2, 25);
        int age = (int) ageField.get(user2);
        System.out.println("年龄：" + age);
    }
}
